//
//  BankViewController.m
//  customer
//
//  Created by 往返网络 on 17/8/23.
//  Copyright © 2017年 com. All rights reserved.
//

#import "BankViewController.h" //银行卡
#import "BangBankWebviewViewController.h" //绑定银行卡h5界面
#import "PublicMethod.h"
#define return_tag 1000
#define next_tag 1001
#define delete_tag 1002
//定义查询银行卡URL
#define URL_CHECKBANK [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payMyCard?type=get",BASE_URL]
//定义删除银行卡URL
#define URL_DELETEBANK [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payCloseMyCard?type=get",BASE_URL]
//定义绑定银行卡URL
#define URL_BANGDINGBANK [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/payAddMyCard?type=get",BASE_URL]

@interface BankViewController ()
@property (nonatomic,strong)AFHTTPSessionManager* manger;
@end

@implementation BankViewController
{
    UIView * view1; //添加银行卡界面
    UIView * view2; //银行信息界面
    UIImageView * im; //银行logo
    UILabel * banknamelab ; //银行名称
    UILabel * firstlab;  //银行前4位
    UILabel * endlab; //银行尾号
    NSString * bankname;
    NSString * banknum; //
    NSString * card_type;  //01借记卡 02贷记卡
    NSString * bank_id; // 银行卡id

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;

}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self checkBank]; //检查当前有没有绑定银行卡
    [self createUI];
    // Do any additional setup after loading the view.
}
- (void)checkBank{

    //请求当前有没有银行卡，银行卡的信息等
    // 有银行卡，view2显示，view1隐藏
    
        //请求账号信息，余额等，赋值。。
        UIImageView * ima = [PublicMethod startAnimation];
        
        NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
        
        NSString * url = [NSString stringWithFormat:@"%@&token=%@",URL_CHECKBANK,token];
        
        NSLog(@"查询当前有没有银行卡 url %@",url);
        
        [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            
            if (responseObject) {
                
                NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                
                NSInteger code = [dict[@"code"]integerValue];
                
                if (code == 0) {
                    // 停止动画
                    [ima stopAnimating];
                    NSDictionary * result = dict[@"info"];
                    NSString * open_id = result[@"open_id"];
                    NSLog(@"open_id %@",open_id);
                    if (open_id.length !=0) {
                        //有银行卡
                        view2.hidden = NO;
                        view1.hidden = YES;
                        banknum = result[@"bank_account"];
                        bankname  = result[@"bank_name"];
                        NSLog(@"banknum %@ bankname %@",banknum,bankname);
                        banknamelab.text  = bankname;
                        NSString * bankaccount = banknum;
                        NSLog(@"银行卡号 %@",bankaccount);
                        bank_id = result[@"bank_id"];
                        card_type = result[@"card_type"];
                        NSLog(@"银行卡 类型 %@,id %@",card_type,bank_id);
                        im.image = [UIImage imageNamed:bank_id];
//                        firstlab.text  = [bankaccount substringToIndex:4];
                        endlab.text  = [bankaccount substringFromIndex:bankaccount.length -4];

                    }else{
                    //没有银行卡
                        [ima stopAnimating];
                        ALERT(@"提示", @"亲，需要去网页版(www.91zxt.cn)去绑卡哟～", self, @"确定", nil);
                        view2.hidden = YES;
                        view1.hidden = YES;
                    }
                    
                }else{
                    
                    [ima stopAnimating];
                    ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                    
                }
                
            }
            
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
            
            ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
            
            [ima stopAnimating];
            
        }];
    }

- (void)deleteBank{
    
    //请求当前有没有银行卡，银行卡的信息等
    // 有银行卡，view2显示，view1隐藏
    
    //请求账号信息，余额等，赋值。。
    UIImageView * ima = [PublicMethod startAnimation];
    
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    
    NSString * url = [NSString stringWithFormat:@"%@&token=%@",URL_DELETEBANK,token];
    
    NSLog(@"删除当前有没有银行卡 url %@",url);
    
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"删除银行卡 dict %@",dict);
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                // 停止动画
                [ima stopAnimating];
                //没有银行卡
                NSLog(@"删除成功");
                view2.hidden = YES;
                view1.hidden = NO;
                
            }else{
                
                [ima stopAnimating];
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
            }
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
        [ima stopAnimating];
        
    }];
    
    
    
}

- (void)bangdingBank{
    
    //请求当前有没有银行卡，银行卡的信息等
    // 有银行卡，view2显示，view1隐藏
    
    //请求账号信息，余额等，赋值。。
    UIImageView * ima = [PublicMethod startAnimation];
    
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:USER_TOCKE];
    
    NSString * url = [NSString stringWithFormat:@"%@&token=%@",URL_BANGDINGBANK,token];
    
    NSLog(@"绑定银行卡 url %@",url);
    
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                // 停止动画
                [ima stopAnimating];
               //获取绑定信息  orig sign
                NSString * info = dict[@"info"];
                //字符串类型转dic类型
                NSData *jsonData = [info dataUsingEncoding:NSUTF8StringEncoding];
                NSError *err;
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                    options:NSJSONReadingMutableContainers
                                                                      error:&err];
                NSLog(@"dic %@",dic);
                NSLog(@"dic class %@",[dic class]);
                NSString * orig = [NSString stringWithFormat:@"%@",dic[@"orig"]];
                NSString * sign = [NSString stringWithFormat:@"%@",dic[@"sign"]];
                NSLog(@"orig %@",orig);
                //请求平安银行h5接口
                BangBankWebviewViewController * bankwebvc = [[BangBankWebviewViewController alloc]init];
                bankwebvc.orig  = orig;
                bankwebvc.sign  = sign;
                [self presentViewController:bankwebvc animated:YES completion:nil];
                
                
            }else{
                [ima stopAnimating];
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
            }
            
        }
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
        [ima stopAnimating];
        
    }];
    
    
}


- (void)createUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    float fontsize = 17;
    
    fontsize = SCREEN_H < 667 ? 15 : 19;
    
    if (SCREEN_H == 667) {
        
        fontsize = 17;
    }
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    //设置表头
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    
    //title
    UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, 20.0, SCREEN_W, 90.0/H_BASE*SCREEN_H)];
    titlelab.text = @"我的银行卡";
    
    titlelab.textColor = [UIColor whiteColor];
    
    [self.view addSubview:titlelab];
    
    titlelab.textAlignment = NSTextAlignmentCenter;
    
    titlelab.font = [UIFont systemFontOfSize:fontsize];
    
    UILabel * leftlable  = [[UILabel alloc]initWithFrame:CGRectMake(0, 20+14.0/1334*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    leftlable.textAlignment = NSTextAlignmentCenter;
    NSString * endstr = @"\U0000e697";
    NSString * text = [NSString stringWithFormat:@"%@%@",endstr,@"返回"];
    leftlable.attributedText = [self changeLabelWithText2:text andStartplace:endstr andendplae:nil andfontsize:fontsize-2];
    leftlable.textColor = [UIColor whiteColor];
    [self.view addSubview:leftlable];
    
    UIButton * returnbtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 150.0/W_BASE*SCREEN_W, 150.0/H_BASE*SCREEN_H)];
    [returnbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    returnbtn.tag = return_tag;
    [self.view addSubview:returnbtn];
    
    UIView * backview = [[UIView alloc]initWithFrame:CGRectMake(0, 127.0/H_BASE*SCREEN_H, SCREEN_W, SCREEN_H-127.0/H_BASE*SCREEN_H)];
    backview.backgroundColor = COLORRGBA(239, 239, 239, 1);
    [self.view addSubview:backview];
    
    view1 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(titleview.frame)+30.0/H_BASE*SCREEN_H, SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    view1.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view1];
    UILabel * iconlab = [[UILabel alloc]initWithFrame:CGRectMake(20.0/W_BASE*SCREEN_W, 0,50.0/W_BASE*SCREEN_W , 80.0/H_BASE*SCREEN_H)];
    iconlab.text = @"\U0000e69a";
    iconlab.font = [UIFont fontWithName:@"iconfont" size:fontsize+10];
    [view1 addSubview:iconlab];
    iconlab.textColor = COLORRGBA(102, 102, 102, 1);
    //旋转45
    iconlab.transform = CGAffineTransformMakeRotation(M_PI/4);
    
    UILabel * banklab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconlab.frame)+20.0/W_BASE*SCREEN_W, 0, 180.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    banklab.text = @"添加银行卡";
    banklab.textColor = COLORRGBA(153, 153, 153, 1);
    [view1 addSubview:banklab];
    banklab.font = [UIFont systemFontOfSize:fontsize-3];
    
    UILabel * rightlab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W - 60.0/W_BASE*SCREEN_W, 0, 40.0 /W_BASE*SCREEN_W,80.0/H_BASE*SCREEN_H)];
    rightlab.textColor = COLORRGBA(153, 153, 153, 1);
    [view1 addSubview:rightlab];
    rightlab.text = @"\U0000e6a7";
    rightlab.font = [UIFont fontWithName:@"iconfont" size:fontsize+5];
    
    UIButton * addbtn = [[UIButton alloc]initWithFrame:view1.bounds];
    [addbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    [view1 addSubview:addbtn];
    addbtn.tag = next_tag;
    view1.hidden = YES;
    
    view2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(titleview.frame)+30.0/H_BASE*SCREEN_H, SCREEN_W, 300.0/H_BASE*SCREEN_H)];
    view2.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view2];
    
    im = [[UIImageView alloc]initWithFrame:CGRectMake(25.0/W_BASE*SCREEN_W, 20.0/H_BASE*SCREEN_H, 80.0/W_BASE*SCREEN_W, 80.0/W_BASE*SCREEN_W)];
    im.backgroundColor = [UIColor whiteColor];
    [view2 addSubview:im];
    banknamelab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(im.frame)+15.0/W_BASE*SCREEN_W, CGRectGetMinY(im.frame), 400.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
//    banknamelab.text = @"中国建设银行储蓄银行";
    banknamelab.font = [UIFont systemFontOfSize:fontsize+1];
    [view2 addSubview:banknamelab];
    
    UILabel * chuxualab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W-125.0/W_BASE*SCREEN_W, CGRectGetMinY(im.frame), 100.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    chuxualab.text  = @"储蓄卡";
    chuxualab.textColor = COLORRGBA(153, 153, 153, 1);
    [view2 addSubview:chuxualab];
    chuxualab.textAlignment = NSTextAlignmentRight;
    chuxualab.font = [UIFont systemFontOfSize:fontsize-3];
    
    float min_distance = (SCREEN_W - 50.0/W_BASE*SCREEN_W-480.0/W_BASE*SCREEN_W)/3.0;
    float min_w = 120.0/W_BASE*SCREEN_W;
    firstlab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(im.frame), CGRectGetMaxY(im.frame), min_w, 125.0/H_BASE*SCREEN_H)];
    firstlab.text = @"****";
//    firstlab.backgroundColor = [UIColor purpleColor];
    firstlab.font = [UIFont systemFontOfSize:fontsize+4];
    [view2 addSubview:firstlab];
    firstlab.textColor = COLORRGBA(102, 102, 102, 1);
    
    UILabel * secondlab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(firstlab.frame)+min_distance, CGRectGetMinY(firstlab.frame), min_w, CGRectGetHeight(firstlab.frame))];
    secondlab.text = @"****";
    secondlab.textAlignment = NSTextAlignmentCenter;
    secondlab.font = [UIFont systemFontOfSize:fontsize+4];
    [view2 addSubview:secondlab];
    secondlab.textColor = COLORRGBA(102, 102, 102, 1);
    
    UILabel * thirdlab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(secondlab.frame)+min_distance, CGRectGetMinY(firstlab.frame), min_w, CGRectGetHeight(firstlab.frame))];
    thirdlab.text = @"****";
    thirdlab.textAlignment = NSTextAlignmentCenter;
    thirdlab.font = [UIFont systemFontOfSize:fontsize+4];
    [view2 addSubview:thirdlab];
    thirdlab.textColor = COLORRGBA(102, 102, 102, 1);
    
    endlab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W-min_w-25.0/W_BASE*SCREEN_W, CGRectGetMinY(firstlab.frame), min_w, CGRectGetHeight(firstlab.frame))];
//    endlab.text = @"1938";
    endlab.font = [UIFont systemFontOfSize:fontsize+4];
    [view2 addSubview:endlab];
//    endlab.backgroundColor = [UIColor purpleColor];
    endlab.textAlignment = NSTextAlignmentRight;
    endlab.textColor = COLORRGBA(102, 102, 102, 1);
   
    UILabel * phonelab = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMinX(im.frame), CGRectGetMaxY(firstlab.frame), 400.0/W_BASE*SCREEN_W, 40.0/H_BASE*SCREEN_H)];
    phonelab.textAlignment = NSTextAlignmentLeft;
    NSString  * phone = [[NSUserDefaults standardUserDefaults]objectForKey:USERDEFAULTS_PHONE];
    NSString * startstr = [phone substringToIndex:3];
    NSString * endstring = [phone substringFromIndex:7];
    phonelab.text  = [NSString stringWithFormat:@"手机号: %@****%@",startstr,endstring];
    NSString * text1 = @"手机号: ";
    NSString * endstr1 = [NSString stringWithFormat:@"%@****%@",startstr,endstring];
    phonelab.attributedText = [self changeLabelWithText:phonelab.text andStartplace:text1 andendplae:endstr1 andfontsize:fontsize-1];
    [view2 addSubview:phonelab];
    
    UIButton * deletebtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_W- 125.0/W_BASE*SCREEN_W, CGRectGetMinY(phonelab.frame), 100.0/W_BASE*SCREEN_W, CGRectGetHeight(phonelab.frame))];
    deletebtn.tag = delete_tag;
    [deletebtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    [view2 addSubview:deletebtn];
    
    UILabel * deletelab = [[UILabel alloc]initWithFrame:CGRectMake(SCREEN_W- 125.0/W_BASE*SCREEN_W, CGRectGetMinY(phonelab.frame), 100.0/W_BASE*SCREEN_W, CGRectGetHeight(phonelab.frame))];
    deletelab.text = @"删除";
    deletelab.textColor = COLORRGBA(47, 165, 255, 1);
    deletelab.textAlignment = NSTextAlignmentRight;
    deletelab.font = [UIFont systemFontOfSize:fontsize-3];
    [view2 addSubview:deletelab];
    
}
#pragma mark  -  -  起始地＋发货人名（终止地＋收货人名）格式化 － － －-- - -  -
-(NSMutableAttributedString*)changeLabelWithText2:(NSString*)needText andStartplace:(NSString *)startplace andendplae:(NSString *)endplace andfontsize:(float)fontsize
{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:needText];
    NSInteger startlength = startplace.length;
    //起始格式化
    [attrString addAttribute:NSFontAttributeName value:[UIFont fontWithName:@"iconfont" size:fontsize+2] range:NSMakeRange(0,startlength)];
    //尾部格式化
    [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:fontsize] range:NSMakeRange(startlength , needText.length  - startlength)];
    return attrString;
    
}

-(NSMutableAttributedString*)changeLabelWithText:(NSString*)needText andStartplace:(NSString *)startplace andendplae:(NSString *)endplace andfontsize:(float)fontsize
{
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:needText];
    NSInteger startlength = startplace.length;
    //起始格式化
    [attrString addAttribute:NSForegroundColorAttributeName value:COLORRGBA(153, 153, 153, 1) range:NSMakeRange(0,startlength)];
    //    //尾部格式化
    [attrString addAttribute:NSForegroundColorAttributeName value:COLORRGBA(102, 102, 102, 1) range:NSMakeRange(startlength , needText.length  - startlength)];
    return attrString;
}
#pragma mark - - - - - - - - - - -  Action - - - - - - - - - - - - -
- (void)enterClick:(UIButton *)btn{
    
    switch (btn.tag) {
        case return_tag:
            //返回
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case next_tag:
            //下一步，进入webview，跳转选择银行
        {
            ALERT(@"提示", @"亲，需要去网页版(www.91zxt.cn)去绑卡哟～", self, @"确定", nil);
//            ALERT(@"提示", @"选择银行", self, @"确定", nil);
//            [self bangdingBank];
//            BangBankWebviewViewController * bangdingvc = [[BangBankWebviewViewController alloc]init];
//            [self.navigationController presentViewController:bangdingvc animated:YES completion:nil];
//            view2.hidden = NO;
//            view1.hidden = YES;
            break;
        }
        case delete_tag:
        {
         //删除银行卡
            UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            UIAlertAction * cancel  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            UIAlertAction * delte = [UIAlertAction actionWithTitle:@"删除当前银行卡" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self deleteBank];
            }];
            [alert addAction:cancel];
            [alert addAction:delte];
            [self presentViewController:alert animated:YES completion:nil];
            
            }
    }
}
#pragma mark - - -- - - - 懒加载 ---- - -- - -

- (AFHTTPSessionManager*)manger{
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
    }
    
    return _manger;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
